package org.szgb.console.zx.task.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.szgb.console.sys.todo.mapper.SysTodoMapper;
import org.szgb.console.sys.todo.service.SysTodoService;
import org.szgb.console.sys.user.entity.SysUser;
import org.szgb.console.sys.user.mapper.SysUserMapper;
import org.szgb.console.utils.Page;
import org.szgb.console.utils.UUIDUtil;
import org.szgb.console.zx.plan.entity.ZxPlan;
import org.szgb.console.zx.plan.mapper.ZxPlanMapper;
import org.szgb.console.zx.task.entity.ZxTask;
import org.szgb.console.zx.task.entity.ZxTaskForm;
import org.szgb.console.zx.task.mapper.ZxTaskFormMapper;
import org.szgb.console.zx.task.mapper.ZxTaskMapper;
import org.szgb.core.base.entity.ApprovalDto;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
@Service
public class ZxTaskService {
    private final ZxTaskMapper zxTaskMapper;
    private final ZxPlanMapper zxPlanMapper;
    private final ZxTaskFormMapper zxTaskFormMapper;
    private final SysUserMapper sysUserMapper;
    private final SysTodoMapper sysTodoMapper;

    private final SysTodoService sysTodoService;

    @Autowired
    public ZxTaskService(ZxTaskMapper zxTaskMapper, SysTodoService sysTodoService, ZxPlanMapper zxPlanMapper, ZxTaskFormMapper zxTaskFormMapper, SysUserMapper sysUserMapper,SysTodoMapper sysTodoMapper) {
        this.zxTaskMapper = zxTaskMapper;
        this.sysTodoService = sysTodoService;
        this.zxPlanMapper = zxPlanMapper;
        this.zxTaskFormMapper = zxTaskFormMapper;
        this.sysUserMapper = sysUserMapper;
        this.sysTodoMapper = sysTodoMapper;
    }

    @Transactional(readOnly = true)
    public ZxTask get(String id) {
        return zxTaskMapper.get(id);
    }

    @Transactional(readOnly = true)
    public List<ZxTask> findList(ZxTask zxTask) {
        if (zxTask != null && zxTask.getPageDto() != null) {
            Page<ZxTask> page = new Page<>(zxTask.getPageDto());
            page.setFirst((page.getPageNo() - 1) * page.getPageSize());
            zxTask.setPage(page);
        }
        return zxTaskMapper.findList(zxTask);
    }

    @Transactional(readOnly = true)
    public Integer getCount(ZxTask zxTask) {
        return zxTaskMapper.getCount(zxTask);
    }

    @Transactional()
    public void save(ZxTask zxTask) {
        // 检查实体对象的ID是否为null，判断是否为新实体
        if (zxTask.getId() == null || zxTask.getId().isEmpty()) {
            // 对于新实体，设置创建者信息
            zxTask.setCreatedBy(zxTask.getUpdatedBy());
            // 添加UUID
            zxTask.setId(UUIDUtil.getUUID());
            // 执行插入操作
            zxTaskMapper.insert(zxTask);
            // 返回成功插入的信息
        } else {
            // 执行更新操作
            zxTaskMapper.update(zxTask);
        }
    }

    @Transactional
    public void delete(String ids) {
        zxTaskMapper.delete(ids.split(","));
    }

    @Transactional
    public void assign(ZxTask zxTask) throws IOException, InterruptedException {
        zxTask.setStatus(1);
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        zxTaskMapper.update(zxTask);
        ZxTask task = zxTaskMapper.get(zxTask.getId());
        // 处理待办
        sysTodoService.approval(task.getId(), task.getUpdatedBy().getId());
        // 向负责人和作业组成员发送待办
        String[] userArray = Stream.concat(Stream.of(task.getLeader().getId()), Arrays.stream(task.getMemberIds().split(","))).toArray(String[]::new);
        sysTodoService.createTodoAndRobotSend(2, 3, sysUserMapper.getByIdArray(userArray), task.getId(), "【" + task.getZxPlan().getName() + "】专项任务已下发", "【" + task.getLocation().getName() + "】该专项的任务已下发，请及时处理");

    }

    @Transactional
    public void reAssign(ZxTask zxTask) throws IOException, InterruptedException {
        // 删除旧的待办
        ZxTask oldTask = zxTaskMapper.get(zxTask.getId());
        String[] oldUserArray = Stream.concat(Stream.of(oldTask.getLeader().getId()), Arrays.stream(oldTask.getMemberIds().split(","))).toArray(String[]::new);
        sysTodoMapper.deleteByUserIds(oldUserArray);

        zxTask.setStatus(1);
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        zxTaskMapper.update(zxTask);
        ZxTask task = zxTaskMapper.get(zxTask.getId());
        // 处理待办
        sysTodoService.approval(task.getId(), task.getUpdatedBy().getId());
        // 向负责人和作业组成员发送待办
        String[] userArray = Stream.concat(Stream.of(task.getLeader().getId()), Arrays.stream(task.getMemberIds().split(","))).toArray(String[]::new);
        sysTodoService.createTodoAndRobotSend(2, 3, sysUserMapper.getByIdArray(userArray), task.getId(), "【" + task.getZxPlan().getName() + "】专项任务已下发", "【" + task.getLocation().getName() + "】该专项的任务已下发，请及时处理");

    }

    @Transactional
    public void submitForm(List<ZxTaskForm> zxTaskFormList, ZxTask zxTask) throws IOException, InterruptedException {
        ZxPlan zxPlan = zxPlanMapper.get(zxTask.getZxPlan().getId());
        // 处理待办
        sysTodoService.approval(zxTask.getId(), zxTask.getUpdatedBy().getId());
        // 提交表单
        zxTaskFormMapper.updateBatch(zxTaskFormList);
        // 查询是否有剩余表单
        ZxTaskForm zxTaskForm = new ZxTaskForm();
        zxTaskForm.setTask(new ZxTask(zxTask.getId()));
        zxTaskForm.setIsFinish(false);
        List<ZxTaskForm> list = zxTaskFormMapper.findList(zxTaskForm);
        if (!zxTaskFormList.isEmpty() || list == null || list.isEmpty()) {
            zxTask.setStatus(2);
            zxTaskMapper.update(zxTask);
            // 向牵头人发送审批待办
            ArrayList<SysUser> userArrayList = new ArrayList<>();
            userArrayList.add(sysUserMapper.get(zxPlan.getLeader().getId()));
            sysTodoService.createTodoAndRobotSend(3, 1, userArrayList, zxTask.getId(), "【" + zxPlan.getName() + "】专项任务已完成", "【" + zxTask.getLocation().getName() + "】专项任务已完成，请及时审批");
        }
    }

    @Transactional
    public void leaderApproval(ApprovalDto approvalDto, SysUser updateUser) throws IOException, InterruptedException {
        sysTodoService.approval(approvalDto.getId(), updateUser.getId());
        ZxTask zxTask = zxTaskMapper.get(approvalDto.getId());
        ZxPlan zxPlan = zxPlanMapper.get(zxTask.getZxPlan().getId());
        if (approvalDto.getIsApproval()) {
            // 设置状态为归档
            zxTask.setStatus(3);
            zxTask.setUpdatedBy(updateUser);
            zxTaskMapper.update(zxTask);
            // 查询任务是否全部完成
            ZxTask task = new ZxTask();
            task.setZxPlan(zxPlan);
            List<ZxTask> list = zxTaskMapper.findList(task).stream().filter(item -> item.getStatus() != 3).toList();
            if (list.isEmpty()) {
                // 如果全部完成，更改计划状态为完成
                zxPlan.setStatus(2);
                zxPlan.setUpdatedBy(updateUser);
                zxPlanMapper.update(zxPlan);
                // 发送审批至工班长
                List<SysUser> foremanList = sysUserMapper.getUserInDepartmentWithRole(zxPlan.getResponsible().getId(), "45b016b7-f50e-44ea-84b4-c70462459c1d");
                sysTodoService.createTodoAndRobotSend(4, 3, foremanList, zxPlan.getId(), "【" + zxPlan.getName() + "】专项计划待处理", "【" + zxTask.getLocation().getName() + "】专项计划已完成请尽快审批");
            }
        } else {
            // 清除负责人、成员、日期、退回状态重新派发
            zxTaskMapper.returnTask(zxTask.getId());
            // 发送知会待办到综合员
            List<SysUser> userList = sysUserMapper.getUserInDepartmentWithRole(zxPlan.getResponsible().getId(), "b157bbc6-e4e0-4587-a4c4-bc4dced82475");
            sysTodoService.createTodoAndRobotSend(8, 3, userList, zxTask.getId(), "【" + zxPlan.getName() + "】专项任务待处理", "【" + zxTask.getLocation().getName() + "】专项的任务被退回需要重新下发");
        }
    }

    @Transactional
    public void leaderApprovalReturn(String taskId) throws IOException, InterruptedException {
        ZxTask zxTask = zxTaskMapper.get(taskId);
        ZxPlan zxPlan = zxPlanMapper.get(zxTask.getZxPlan().getId());
        // 清除负责人、成员、日期、退回状态重新派发
        zxTaskMapper.returnTask(zxTask.getId());
        // 发送知会待办到综合员
        List<SysUser> userList = sysUserMapper.getUserInDepartmentWithRole(zxPlan.getResponsible().getId(), "b157bbc6-e4e0-4587-a4c4-bc4dced82475");
        sysTodoService.createTodoAndRobotSend(8, 3, userList, zxTask.getId(), "【" + zxPlan.getName() + "】专项任务待处理", "【" + zxTask.getLocation().getName() + "】专项的任务被退回需要重新下发");

    }
}
